package com.zbkj.service.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.zbkj.common.constants.Constants;
import com.zbkj.common.enums.SmsTypeEnum;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.sms.AliSmsUtil;
import com.zbkj.common.utils.CommonUtil;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.service.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther:
 * @Date: 2024/9/11 19:16
 * @Description:
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisUtil redisUtil;

    public void sendCodeSms(String phone, SmsTypeEnum smsTypeEnum) {
        Integer code = CommonUtil.randomCount(111111, 999999);
        AliSmsUtil.sendCode(phone, code);
        this.saveCodeCach(phone,String.valueOf(code),smsTypeEnum);
    }

    @Override
    public void checkValidateCode(String phone, String code, SmsTypeEnum smsTypeEnum) {
        if("000000".equals(code)) {
            return;
        }
        String codeKey = this.getCodeCachKey(phone,smsTypeEnum);
        String sendCode = redisUtil.get(codeKey);
        if(StringUtils.isBlank(sendCode)) {
            throw new CommonException("验证码已过期");
        }
        if (!sendCode.equals(code)) {
            throw new CommonException("验证码错误");
        }
        //删除验证码
        redisUtil.delete(codeKey);
    }

    private String getCodeCachKey(String phone, SmsTypeEnum smsTypeEnum) {
        return String.format(Constants.SMS_VALIDATE_PHONE,smsTypeEnum.getType(),phone);
    }

    private void saveCodeCach(String phone, String code, SmsTypeEnum smsTypeEnum) {
        String codeKey = this.getCodeCachKey(phone,smsTypeEnum);
        redisUtil.set(codeKey,code,Constants.SMS_VALIDATE_EXPIRE);
    }
}
